//
//  UIView+Lc.m
//  18Birdies
//
//  Created by Lc on 15/3/31.
//  Copyright (c) 2015年 Lc. All rights reserved.
//

#import "LcUIUtility.h"
#import "UIView+Lc.h"
#import "UIImage+Lc.h"

@implementation UIView (Lc)

- (void)enableBackgroundColorIfDebug {
#ifdef DEBUG
  self.backgroundColor = [LcUIUtility debugBackgroundColor];
#endif
}

@dynamic width, height, posX, posY, centerPos, top, right, left;

- (CGFloat)width {
  return self.frame.size.width;
}

- (CGFloat)height {
  return self.frame.size.height;
}

- (CGFloat)posX {
  return self.frame.origin.x;
}

- (CGFloat)posY {
  return self.frame.origin.y;
}

- (CGFloat)top {
  return self.frame.origin.y;
}

- (CGFloat)bottom {
  return self.frame.origin.y + self.frame.size.height;
}

- (CGFloat)left {
  return self.posX;
}

- (CGFloat)right {
  return self.brPos.x;
}

- (CGSize)size {
  return CGSizeMake(self.width, self.height);
}

- (void)setSize:(CGSize)size {
  self.width = size.width;
  self.height = size.height;
}

- (CGPoint)brPos {
  return CGPointMake([self posX] + [self width], [self posY] + [self height]);
}

- (CGFloat)centerX {
  return self.center.x;
}

- (void)setCenterX:(CGFloat)centerX {
  CGPoint centerPoint = self.center;
  centerPoint.x = centerX;
  self.center = centerPoint;
}

- (CGFloat)centerY {
  return self.center.y;
}

- (void)setCenterY:(CGFloat)centerY {
  CGPoint centerPoint = self.center;
  centerPoint.y = centerY;
  self.center = centerPoint;
}

- (CGPoint)centerPos {
  return CGPointMake([self width] / 2, [self height] / 2);
}

- (void)setCenterPos:(CGPoint)pos {
  if (isnan(pos.x) || isnan(pos.y)) {
    self.frame = CGRectMake(-10000, -10000, self.width, self.height);
  } else {
    self.frame = CGRectMake(pos.x - self.width / 2, pos.y - self.height / 2,
                            self.width, self.height);
  }
}

- (void)setTop:(CGFloat)top {
  [self setPosY:top];
}

- (void)setBottom:(CGFloat)bottom {
  CGRect frame = self.frame;
  frame.origin.y = bottom - frame.size.height;
  self.frame = frame;
}

- (void)setWidth:(CGFloat)width {
  self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, width,
                          self.frame.size.height);
}

- (void)setHeight:(CGFloat)height {
  self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y,
                          self.frame.size.width, height);
}

- (void)setPosX:(CGFloat)posx {
  self.frame = CGRectMake(posx, self.frame.origin.y, self.frame.size.width,
                          self.frame.size.height);
}

- (void)setLeft:(CGFloat)left {
  [self setPosX:left];
}

- (void)setRight:(CGFloat)right {
  [self setPosX:right - self.width];
}

- (void)setPosY:(CGFloat)posy {
  self.frame = CGRectMake(self.frame.origin.x, posy, self.frame.size.width,
                          self.frame.size.height);
}

- (void)moveUp:(CGFloat)len {
  self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y - len,
                          self.frame.size.width, self.frame.size.height);
}

- (void)moveRight:(CGFloat)len {
  self.frame = CGRectMake(self.frame.origin.x + len, self.frame.origin.y,
                          self.frame.size.width, self.frame.size.height);
}

- (void)centerToView:(UIView*)view {
  [self setPosX:([view width] - [self width]) / 2];
  [self setPosY:([view height] - [self height]) / 2];
}

- (void)centerToRect:(CGRect)rect {
  [self setPosX:(rect.size.width - [self width]) / 2];
  [self setPosY:(rect.size.height - [self height]) / 2];
}

- (void)showLoadingIndicator {
  [self removeLoadingIndicator];
  UIActivityIndicatorView* loadingView =
      [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
  loadingView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
  [loadingView startAnimating];
  [loadingView centerToView:self];
  [self addSubview:loadingView];
}

- (void)removeLoadingIndicator {
  for (UIView* loadingView in self.subviews) {
    if ([loadingView isKindOfClass:[UIActivityIndicatorView class]]) {
      [loadingView removeFromSuperview];
      break;
    }
  }
}

- (void)removeAllSubviews {
  for (UIView* subview in self.subviews) {
    [subview removeFromSuperview];
  }
}

- (void)hideAllSubviews {
  for (UIView* subview in self.subviews) {
    subview.hidden = YES;
  }
}

- (void)removeAllGestures {
  for (int i = 0; i < self.gestureRecognizers.count; ++i) {
    UIGestureRecognizer* gesture = self.gestureRecognizers[i];
    [self removeGestureRecognizer:gesture];
  }
}

- (UIView*)findFirstResponder {
  if ([self isFirstResponder]) {
    return self;
  } else {
    for (UIView* subView in self.subviews) {
      UIView* firstResponderView = [subView findFirstResponder];
      if (firstResponderView != nil) {
        return firstResponderView;
      }
    }
  }
  return nil;
}

+ (void)hideKeyBoard {
  [[UIApplication sharedApplication].keyWindow endEditing:YES];
}

- (void)hideKeyBoard {
  [[UIApplication sharedApplication].keyWindow endEditing:YES];
}

- (UIImage*)snapShot {
  return [UIImage snapShotFromUIView:self targetRect:self.bounds];
}

#pragma mark -

- (void)setEqualWidthHeightLayoutWithSuperView:(UIView*)superView {
  [self setEdgeInsets:UIEdgeInsetsZero superView:superView];
}

- (void)setEdgeInsets:(UIEdgeInsets)edgeInsets superView:(UIView*)superView {
  if (superView == nil) {
    return;
  }
  self.translatesAutoresizingMaskIntoConstraints = NO;
  NSLayoutConstraint* topConstraint =
      [self constraintRelatedByEqualWithAttribute:NSLayoutAttributeTop
                                           toItem:superView
                                         constant:edgeInsets.top];
  NSLayoutConstraint* bottomConstraint =
      [self constraintRelatedByEqualWithAttribute:NSLayoutAttributeBottom
                                           toItem:superView
                                         constant:edgeInsets.bottom];
  NSLayoutConstraint* leftConstraint =
      [self constraintRelatedByEqualWithAttribute:NSLayoutAttributeLeading
                                           toItem:superView
                                         constant:edgeInsets.left];
  NSLayoutConstraint* rightConstraint =
      [self constraintRelatedByEqualWithAttribute:NSLayoutAttributeTrailing
                                           toItem:superView
                                         constant:edgeInsets.right];
  [superView addConstraints:@[ topConstraint, bottomConstraint, leftConstraint, rightConstraint ]];
}

- (NSLayoutConstraint*)constraintRelatedByEqualWithAttribute:(NSInteger)attribute
                                                      toItem:(UIView*)toItem
                                                    constant:(CGFloat)constant {
  return [NSLayoutConstraint constraintWithItem:self
                                      attribute:attribute
                                      relatedBy:NSLayoutRelationEqual
                                         toItem:toItem
                                      attribute:attribute
                                     multiplier:1
                                       constant:constant];
}

// 水平线性渐变
- (void)addHorizontalLinearLayer:(CGRect)frame colors:(NSArray*)colors {
  [self addLinearLayer:frame colors:colors startPoint:CGPointMake(0, 0) endPoint:CGPointMake(1, 0)];
}

// 垂直线性渐变
- (void)addVerticalLinearLayer:(CGRect)frame colors:(NSArray*)colors {
  [self addLinearLayer:frame colors:colors startPoint:CGPointMake(0, 0) endPoint:CGPointMake(0, 1)];
}

// 默认渐变
- (void)addLinearLayer:(CGRect)frame colors:(NSArray*)colors {
  [self addLinearLayer:frame colors:colors startPoint:CGPointMake(0, 0) endPoint:CGPointMake(1, 1)];
}

- (void)addLinearLayer:(CGRect)frame colors:(NSArray*)colors startPoint:(CGPoint)startPoint  endPoint:(CGPoint)endPoint{
  CAGradientLayer *gradientLayer = [CAGradientLayer layer];
  gradientLayer.colors = colors;
  // gradientLayer.locations = @[@0.3, @0.5, @1.0];
  gradientLayer.startPoint = startPoint;
  gradientLayer.endPoint = endPoint;
  gradientLayer.frame = frame;
  [self.layer addSublayer:gradientLayer];
}

- (void)clearLinearLayer {
  for (int i = 0; i < self.layer.sublayers.count; i++) {
    CALayer* layer = self.layer.sublayers[i];
    if ([layer isKindOfClass:CAGradientLayer.class]) {
      [layer removeFromSuperlayer];
    }
  }
}

@end

@implementation UIView (UIViewController)

- (UIViewController*)parentViewController {
  id parentViewController = [self nextResponder];
  while (![parentViewController isKindOfClass:[UIViewController class]] && parentViewController != nil) {
    parentViewController = [parentViewController nextResponder];
  }
  if ([parentViewController isKindOfClass:[UIViewController class]]) {
    return parentViewController;
  }
  return nil;
}

@end

@implementation UIView (UIRectCorner)

- (void)setCorner:(UIRectCorner)corner cornerRaius:(CGFloat)cornerRadius {
  if (cornerRadius == 0) {
    [self clearCorner];
    return;
  }
  UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corner cornerRadii:CGSizeMake(cornerRadius, cornerRadius)];
  CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
  maskLayer.frame = self.bounds;
  maskLayer.path = maskPath.CGPath;
  self.layer.mask = maskLayer;
}

- (void)clearCorner {
  self.layer.mask = nil;
}

@end

